package threads;

import java.util.ArrayList;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class testThread {
    static Account account=new Account();
	public static void main(String[] args) {
		
		ExecutorService executor=Executors.newFixedThreadPool(2);
		executor.execute(new WithdrawTask());
		executor.execute(new DepostTask());

	}
    
	
	
	
	private static class WithdrawTask implements Runnable{

		@Override
		public void run() {
		    while(true)
			account.withdraw();
		}
		
	}
	
	private static class DepostTask implements Runnable{

		@Override
		public void run() {
			while(true) {
			account.depost(10);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO 自动生成的 catch 块
				e.printStackTrace();
			}
			}
			
		}
		
	}
	
	private static class Account{
		
		ArrayList<Integer> list=new ArrayList<>();
		private static Lock lock=new ReentrantLock();
		private static Condition newDeposit=lock.newCondition();
		
		public void withdraw() {
			lock.lock();
			while(list.size()==0) {
				try {
					System.out.println("现在没有数字可以删除");
					newDeposit.await();
				} catch (InterruptedException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
			list.remove(list.size()-1);
			System.out.println("删除成功");
			lock.unlock();
		}
		
		public void depost(int amount) {
			lock.lock();
			list.add(amount);
			System.out.println("添加成功");
			newDeposit.signal();
			lock.unlock();
		}
		
		
		
		
	}
}
